const jwt = require('jsonwebtoken');
const { User, Recipe, Food, Post, DietRecord, SportRecord } = require('../models');
const bcrypt = require('bcryptjs');
const { Op } = require('sequelize');
require('dotenv').config();

module.exports = {
  // 管理员登录
  async login(req, res) {
    try {
      const { username, password } = req.body;

      // 使用固定的admin账号密码验证
      if (username === 'admin' && password === 'admin') {
        // 生成JWT token
        const token = jwt.sign(
          { 
            id: 0, // 管理员ID固定为0
            isAdmin: true 
          },
          process.env.JWT_SECRET,
          { expiresIn: '1d' }
        );

        res.json({
          code: 0,
          data: {
            token,
            user: {
              id: 0,
              username: 'admin',
              nickname: '管理员',
              isAdmin: true
            }
          },
          message: '登录成功'
        });
      } else {
        res.json({
          code: 1,
          message: '用户名或密码错误'
        });
      }
    } catch (error) {
      console.error('管理员登录失败:', error);
      res.json({
        code: 1,
        message: '登录失败'
      });
    }
  },

  // 获取仪表盘数据
  async getDashboardData(req, res) {
    try {
      const today = new Date().toISOString().split('T')[0];

      // 获取各种统计数据
      const [
        totalUsers,
        totalRecipes,
        totalFoods,
        totalPosts,
        todaySports,
        todayDiets
      ] = await Promise.all([
        User.count(),
        Recipe.count(),
        Food.count(),
        Post.count(),
        SportRecord.count({ where: { date: today } }),
        DietRecord.count({ where: { date: today } })
      ]);

      res.json({
        code: 0,
        data: {
          totalUsers,
          totalRecipes,
          totalFoods,
          totalPosts,
          todaySports,
          todayDiets
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      res.json({ code: 1, message: '获取仪表盘数据失败' });
    }
  },

  // 获取用户列表
  async getUsers(req, res) {
    try {
      const { page = 1, limit = 10, search } = req.query;
      const offset = (page - 1) * limit;

      const where = {};
      if (search) {
        where[Op.or] = [
          { username: { [Op.like]: `%${search}%` } },
          { nickname: { [Op.like]: `%${search}%` } }
        ];
      }

      const { count, rows } = await User.findAndCountAll({
        where,
        limit: parseInt(limit),
        offset: parseInt(offset),
        attributes: { exclude: ['password'] },
        order: [['createdAt', 'DESC']]
      });

      res.json({
        code: 0,
        data: {
          total: count,
          list: rows,
          page: parseInt(page),
          limit: parseInt(limit)
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取用户列表失败:', error);
      res.json({ code: 1, message: '获取用户列表失败' });
    }
  },

  // 删除用户
  async deleteUser(req, res) {
    try {
      const { id } = req.params;
      const user = await User.findByPk(id);

      if (!user) {
        return res.json({ code: 1, message: '用户不存在' });
      }

      await user.destroy();
      res.json({ code: 0, message: '删除成功' });
    } catch (error) {
      console.error('删除用户失败:', error);
      res.json({ code: 1, message: '删除用户失败' });
    }
  },

  // 获取运动记录列表
  async getSportRecords(req, res) {
    try {
      console.log('获取运动记录列表');
      const { page = 1, limit = 10 } = req.query;
      const offset = (page - 1) * limit;

      const { count, rows } = await SportRecord.findAndCountAll({
        include: [{
          model: User,
          as: 'user',
          attributes: ['username', 'nickname', 'avatar']
        }],
        order: [['date', 'DESC']],
        offset,
        limit: parseInt(limit)
      });

      res.json({
        code: 0,
        data: {
          list: rows,
          total: count,
          page: parseInt(page)
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取运动记录列表失败:', error);
      res.json({
        code: 1,
        message: '获取运动记录列表失败'
      });
    }
  },

  // 删除运动记录
  async deleteSportRecord(req, res) {
    try {
      const { id } = req.params;
      const record = await SportRecord.findByPk(id);
      
      if (!record) {
        return res.json({
          code: 1,
          message: '记录不存在'
        });
      }

      await record.destroy();
      res.json({
        code: 0,
        message: '删除成功'
      });
    } catch (error) {
      console.error('删除运动记录失败:', error);
      res.json({
        code: 1,
        message: '删除运动记录失败'
      });
    }
  },

  // 获取饮食记录列表
  async getDietRecords(req, res) {
    try {
      const { page = 1, limit = 10 } = req.query;
      const offset = (page - 1) * limit;

      const { count, rows } = await DietRecord.findAndCountAll({
        include: [{
          model: User,
          as: 'user',
          attributes: ['username', 'nickname', 'avatar']
        }],
        order: [['date', 'DESC']],
        offset,
        limit: parseInt(limit)
      });

      res.json({
        code: 0,
        data: {
          list: rows,
          total: count,
          page: parseInt(page)
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取饮食记录列表失败:', error);
      res.json({
        code: 1,
        message: '获取饮食记录列表失败'
      });
    }
  },

  // 删除饮食记录
  async deleteDietRecord(req, res) {
    try {
      const { id } = req.params;
      const record = await DietRecord.findByPk(id);
      
      if (!record) {
        return res.json({
          code: 1,
          message: '记录不存在'
        });
      }

      await record.destroy();
      res.json({
        code: 0,
        message: '删除成功'
      });
    } catch (error) {
      console.error('删除饮食记录失败:', error);
      res.json({
        code: 1,
        message: '删除饮食记录失败'
      });
    }
  },

  // 获取食谱列表
  async getRecipes(req, res) {
    try {
      const { page = 1, limit = 10, search = '' } = req.query;
      const offset = (page - 1) * limit;

      // 构建查询条件
      const where = {};
      if (search) {
        where.name = {
          [Op.like]: `%${search}%`
        };
      }

      // 查询食谱列表
      const { count, rows: recipes } = await Recipe.findAndCountAll({
        where,
        include: [{
          model: User,
          as: 'creator',
          attributes: ['username', 'nickname']
        }],
        order: [['createdAt', 'DESC']],
        offset,
        limit: parseInt(limit)
      });

      res.json({
        code: 0,
        data: {
          total: count,
          list: recipes,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      });
    } catch (error) {
      console.error('获取食谱列表失败:', error);
      res.status(500).json({
        code: 1,
        message: '获取食谱列表失败'
      });
    }
  },

  // 获取食谱详情
  async getRecipeById(req, res) {
    try {
      const { id } = req.params;
      const recipe = await Recipe.findByPk(id, {
        include: [{
          model: User,
          as: 'creator',
          attributes: ['username', 'nickname']
        }]
      });

      if (!recipe) {
        return res.status(404).json({
          code: 1,
          message: '食谱不存在'
        });
      }

      res.json({
        code: 0,
        data: recipe
      });
    } catch (error) {
      console.error('获取食谱详情失败:', error);
      res.status(500).json({
        code: 1,
        message: '获取食谱详情失败'
      });
    }
  },

  // 创建食谱
  async createRecipe(req, res) {
    try {
      const {
        name,
        description,
        ingredients,
        steps,
        cookingTime,
        difficulty,
        category,
        image,
        nutrition,
        tags
      } = req.body;

      // 数据验证
      if (!name || !description || !ingredients || !steps) {
        return res.status(400).json({
          code: 1,
          message: '请填写完整的食谱信息'
        });
      }

      // 创建食谱
      const recipe = await Recipe.create({
        name,
        description,
        ingredients,
        steps,
        cookingTime,
        difficulty,
        category,
        createdBy:1,
        image,
        nutrition,
        tags,
      
      });

      res.json({
        code: 0,
        data: recipe,
        message: '创建食谱成功'
      });
    } catch (error) {
      console.error('创建食谱失败:', error);
      res.status(500).json({
        code: 1,
        message: '创建食谱失败'
      });
    }
  },

  // 更新食谱
  async updateRecipe(req, res) {
    try {
      const { id } = req.params;
      const {
        name,
        description,
        ingredients,
        steps,
        cookingTime,
        difficulty,
        category,
        image,
        nutrition,
        tags
      } = req.body;

      // 查找食谱
      const recipe = await Recipe.findByPk(id);
      if (!recipe) {
        return res.status(404).json({
          code: 1,
          message: '食谱不存在'
        });
      }

      // 数据验证
      if (!name || !description || !ingredients || !steps) {
        return res.status(400).json({
          code: 1,
          message: '请填写完整的食谱信息'
        });
      }

      // 更新食谱信息
      await recipe.update({
        name,
        description,
        ingredients,
        steps,
        cookingTime,
        difficulty,
        category,
        image,
        nutrition,
        tags
      });

      res.json({
        code: 0,
        data: recipe,
        message: '更新食谱成功'
      });
    } catch (error) {
      console.error('更新食谱失败:', error);
      res.status(500).json({
        code: 1,
        message: '更新食谱失败'
      });
    }
  },

  // 删除食谱
  async deleteRecipe(req, res) {
    try {
      const { id } = req.params;
      
      const recipe = await Recipe.findByPk(id);
      if (!recipe) {
        return res.status(404).json({
          code: 1,
          message: '食谱不存在'
        });
      }

      await recipe.destroy();

      res.json({
        code: 0,
        message: '删除成功'
      });
    } catch (error) {
      console.error('删除食谱失败:', error);
      res.status(500).json({
        code: 1,
        message: '删除失败'
      });
    }
  },

  // 获取食物列表
  async getFoods(req, res) {
    try {
      const { page = 1, limit = 10, search = '' } = req.query;
      const offset = (page - 1) * limit;

      const where = {};
      if (search) {
        where.name = {
          [Op.like]: `%${search}%`
        };
      }

      const { count, rows: foods } = await Food.findAndCountAll({
        where,
        limit: parseInt(limit),
        offset: parseInt(offset),
        order: [['id', 'DESC']]
      });

      res.json({
        code: 0,
        data: {
          foods,
          total: count
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取食物列表失败:', error);
      res.json({
        code: 1,
        message: '获取食物列表失败'
      });
    }
  },

  // 获取食物详情
  async getFoodById(req, res) {
    try {
      const { id } = req.params;
      const food = await Food.findByPk(id);
      
      if (!food) {
        return res.json({
          code: 1,
          message: '食物不存在'
        });
      }

      res.json({
        code: 0,
        data: food,
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取食物详情失败:', error);
      res.json({
        code: 1,
        message: '获取食物详情失败'
      });
    }
  },

  // 创建食物
  async createFood(req, res) {
    try {
      const foodData = req.body;
      const food = await Food.create(foodData);

      res.json({
        code: 0,
        data: food,
        message: '创建成功'
      });
    } catch (error) {
      console.error('创建食物失败:', error);
      res.json({
        code: 1,
        message: '创建食物失败'
      });
    }
  },

  // 更新食物
  async updateFood(req, res) {
    try {
      const { id } = req.params;
      const foodData = req.body;
      
      const food = await Food.findByPk(id);
      if (!food) {
        return res.json({
          code: 1,
          message: '食物不存在'
        });
      }

      await food.update(foodData);

      res.json({
        code: 0,
        data: food,
        message: '更新成功'
      });
    } catch (error) {
      console.error('更新食物失败:', error);
      res.json({
        code: 1,
        message: '更新食物失败'
      });
    }
  },

  // 删除食物
  async deleteFood(req, res) {
    try {
      const { id } = req.params;
      
      const food = await Food.findByPk(id);
      if (!food) {
        return res.json({
          code: 1,
          message: '食物不存在'
        });
      }

      await food.destroy();

      res.json({
        code: 0,
        message: '删除成功'
      });
    } catch (error) {
      console.error('删除食物失败:', error);
      res.json({
        code: 1,
        message: '删除食物失败'
      });
    }
  },

  // 获取帖子列表
  async getPosts(req, res) {
    try {
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 10;
      const offset = (page - 1) * limit;
      const search = req.query.search || '';

      const where = {};
      if (search) {
        where[Op.or] = [
          { title: { [Op.like]: `%${search}%` } },
          { content: { [Op.like]: `%${search}%` } }
        ];
      }

      const { count, rows: posts } = await Post.findAndCountAll({
        where,
        include: [{
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }],
        order: [['createdAt', 'DESC']],
        offset,
        limit
      });

      res.json({
        code: 0,
        data: {
          posts,
          total: count
        },
        message: '获取成功'
      });
    } catch (error) {
      console.error('获取帖子列表失败:', error);
      res.json({
        code: 1,
        message: '获取帖子列表失败'
      });
    }
  },

  // 删除帖子
  async deletePost(req, res) {
    try {
      const { id } = req.params;

      // 先查找关联的食谱
      const recipe = await Recipe.findOne({
        where: { postId: id }
      });

      // 如果存在关联的食谱，先解除关联
      if (recipe) {
        await recipe.update({ postId: null });
      }

      // 删除帖子
      const result = await Post.destroy({
        where: { id }
      });

      if (result === 0) {
        return res.json({
          code: 1,
          message: '帖子不存在'
        });
      }

      res.json({
        code: 0,
        message: '删除成功'
      });
    } catch (error) {
      console.error('删除帖子失败:', error);
      res.json({
        code: 1,
        message: '删除失败'
      });
    }
  }
}; 